﻿using System;
using System.Security.Cryptography;
using System.Text;

namespace PlexBB.Data
{
    public abstract class PasswordProtectedEntity
    {
        private const int _passwordSaltLength = 48; // same as in DB type (see MappingTemplate.xml)
        private static readonly HashAlgorithm _hashAlgorithm = SHA384.Create();

        protected abstract byte[] Password { get; set; }

        protected abstract byte[] PasswordSalt { get; set; }

        public void SetPassword(string password)
        {
            if (password == null)
            {
                Password = null;
                PasswordSalt = null;
            }
            else
            {
                // generate new random password salt
                Random random = new Random();
                PasswordSalt = new byte[_passwordSaltLength];
                random.NextBytes(PasswordSalt);

                // set the password itself
                Password = ComputePasswordHash(password);
            }
        }

        public bool ValidatePassword(string password)
        {
            if (Password == null || PasswordSalt == null)
            {
                return false;
            }
            byte[] inputBytes = ComputePasswordHash(password);
            return Util.CompareByteArrays(inputBytes, Password);
        }

        private byte[] ComputePasswordHash(string password)
        {
            if (PasswordSalt == null)
            {
                throw new InvalidOperationException();
            }

            // compute the salt + password SHA1 hash and store it in _password
            byte[] passwordBytes = Encoding.UTF8.GetBytes(password);
            byte[] totalBytes = new byte[passwordBytes.Length + PasswordSalt.Length];
            passwordBytes.CopyTo(totalBytes, 0);
            PasswordSalt.CopyTo(totalBytes, passwordBytes.Length);
            // thread safety?
            return _hashAlgorithm.ComputeHash(totalBytes);
        }
    }
}